<template>
  <div class="confirm-modal">
    <modal ref="modalInstance" :title="title" :disableEscClose="isConfirmed" :staticModal="staticModal" :showClose="showClose" :width="width"
           @close="closeHandler" @closed="closedHandler">
      <div class="confirm-modal-text" v-if="isHtml" v-html="text"></div>
      <div class="confirm-model-text" v-else>{{text}}</div>
      <div class="confirm-modal-opts">
        <button class="btn btn-light" v-if="cancelText" @click="confirm(false)">{{cancelText}}</button>
        <button ref="confirmBtnInstance" class="btn btn-primary" @click="confirm(true)">{{confirmText}}</button>
      </div>
    </modal>
  </div>
</template>

<script>
  import Vue from 'vue'
  import Promise from 'promise'
  import Modal from '../Modal.vue'

  export default {
    components: {Modal},
    data () {
      return {
        confirmText: '确认',
        cancelText: '取消',
        width: '420px',
        title: null,
        text: '',
        isConfirmed: false,
        disableEscClose: false,
        staticModal: true,
        showClose: true,
        resolve: null,
        isHtml: false
      }
    },
    methods: {
      closeHandler () {
        if (this.resolve) {
          this.resolve(this.isConfirmed)
        }
      },
      closedHandler () {
        document.body.removeChild(this.$el)
        this.$destroy()
      },
      confirm (isConfirmed) {
        this.isConfirmed = isConfirmed
        this.$refs.modalInstance.close()
      },
      open () {
        this.$refs.modalInstance.open()
        Vue.nextTick(() => {
          this.$refs.confirmBtnInstance.focus()
        })
        return new Promise((resolve) => {
          this.resolve = resolve
        })
      }
    }
  }
</script>
